#!/bin/bash

ATFRAMEWORK_CMAKE_TOOLSET_THIRD_PARTY_GRPC_HOST_BUILD_DIR="@ATFRAMEWORK_CMAKE_TOOLSET_THIRD_PARTY_GRPC_HOST_BUILD_DIR@" ;
BUILD_THIRD_IS_CROSS="@CMAKE_CROSSCOMPILING@"
BUILD_THIRD_IS_CROSS="$(echo $BUILD_THIRD_IS_CROSS | tr '[:upper:]' '[:lower:]')"
LOW_MEMORY_MODE="@ATFRAMEWORK_CMAKE_TOOLSET_THIRD_PARTY_LOW_MEMORY_MODE@"
LOW_MEMORY_MODE="$(echo $LOW_MEMORY_MODE | tr '[:upper:]' '[:lower:]')"

if [[ "x$LOW_MEMORY_MODE" == "xtrue" ]] || [[ "x$LOW_MEMORY_MODE" == "xyes" ]] || 
    [[ "x$LOW_MEMORY_MODE" == "x1" ]] || [[ "x$LOW_MEMORY_MODE" == "xon" ]]; then
    ALLOW_PARALLEL_BUILD_FLAGS=0 ;
else
    ALLOW_PARALLEL_BUILD_FLAGS=1 ;
fi

set -x ;

# build host grpc_cpp_plugin first
export PATH="$ATFRAMEWORK_CMAKE_TOOLSET_THIRD_PARTY_GRPC_HOST_BUILD_DIR:$PATH" ;

if [[ ! -e "$ATFRAMEWORK_CMAKE_TOOLSET_THIRD_PARTY_GRPC_HOST_BUILD_DIR" ]]; then
    mkdir -p "$ATFRAMEWORK_CMAKE_TOOLSET_THIRD_PARTY_GRPC_HOST_BUILD_DIR" ;    
fi

cd "$ATFRAMEWORK_CMAKE_TOOLSET_THIRD_PARTY_GRPC_HOST_BUILD_DIR" ;

if [[ -e "CMakeCache.txt" ]]; then
    rm -f "CMakeCache.txt" ;
fi

if [[ ! -e "@PROJECT_THIRD_PARTY_HOST_INSTALL_DIR@/bin/grpc_cpp_plugin.exe" ]] && [[ ! -e "@PROJECT_THIRD_PARTY_HOST_INSTALL_DIR@/bin/grpc_cpp_plugin.exe" ]]; then

    env CC= CXX= SDKROOT= @ATFRAMEWORK_CMAKE_TOOLSET_THIRD_PARTY_GRPC_HOST_BUILD_FLAGS_CMD@ "-DCMAKE_INSTALL_PREFIX=@PROJECT_THIRD_PARTY_HOST_INSTALL_DIR@" "-DCMAKE_POLICY_DEFAULT_CMP0091=NEW" ;

    if [[ "x@MSVC@" == "xTrue" ]] || [[ "x@MSVC@" == "xYes" ]] || [[ "x@MSVC@" == "x1" ]]; then

        if [[ $ALLOW_PARALLEL_BUILD_FLAGS -eq 1 ]]; then
            "@CMAKE_COMMAND@" --build . --target install --config Debug -j || "@CMAKE_COMMAND@" --build . --target install --config Debug ;
            "@CMAKE_COMMAND@" --build . --target install --config Release -j || "@CMAKE_COMMAND@" --build . --target install --config Release ;
        else
            "@CMAKE_COMMAND@" --build . --target install --config Debug ;
            "@CMAKE_COMMAND@" --build . --target install --config Release ;
        fi

        if [[ "x@CMAKE_BUILD_TYPE@" != "x" ]] && [[ "x@CMAKE_BUILD_TYPE@" != "xRelease" ]]; then
            if [[ $ALLOW_PARALLEL_BUILD_FLAGS -eq 1 ]]; then
                "@CMAKE_COMMAND@" --build . --target install --config "@CMAKE_BUILD_TYPE@" -j || "@CMAKE_COMMAND@" --build . --target install --config "@CMAKE_BUILD_TYPE@" ;
            else
                "@CMAKE_COMMAND@" --build . --target install --config "@CMAKE_BUILD_TYPE@" ;
            fi
        fi

    else

        if [[ $ALLOW_PARALLEL_BUILD_FLAGS -eq 1 ]]; then
            "@CMAKE_COMMAND@" --build . --target install --config Release -j || "@CMAKE_COMMAND@" --build . --target install --config Release ;
        else
            "@CMAKE_COMMAND@" --build . --target install --config Release ;
        fi

    fi

fi
